0

Here is the code snippet I read from google's gflags source code

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;
}

and the macros define 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

Clearly, the author prefer strtoll to strtol. According the man page of these two functions, one returns long long int, and the other returns long int. They are all ok if you only want an int32, right?

So what's the difference between those two functions? Why strtoll is preferred?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
coinsyx
  • 643
  • 2
  • 7
  • 13
  • It is used in range. If we use an integer of 32 bit then we have ran out of range when we try to store a mobile number, If we use long long int the range exceeds than previous so that we can store more numbers. – Q_SaD Mar 08 '14 at 06:10

2 Answers2

1

Your question is actually: "whys is strto64 used here when the flag is FV_INT32 ?":

This code seems to prefer strto64 because of this check:

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

So it first tries to gulp as much as possible of the number, hence strto64. After it has that it can comfortably check it that fits in 32 bits.


About strtoll: long long is guaranteed to be at least 64 bits wide. So it makes sense to prefer it for strto64.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • But you only want an int32, right? You can gulp a _long long int_, but finally you will cast it into an int32. If the number is larger than int32, it still returns false. So a _long int_ seems suffice. – coinsyx Mar 08 '14 at 06:16
  • @coinsyx A `long int` isn't guaranteed to be 64 bits, like a `long long` is. – cnicutar Mar 08 '14 at 06:17
0

On systems that support long long int, it's at least a 64 bit integer. On the other hand, the guarantee for long int is that it is at least a 32 bit integer. On some systems / with some compilers, long int is a 64 bit integer. On others, it's only 32 bits. The Google header is hoping that a long int is indeed 64 bits on systems that don't provide strtoll or strtoq because otherwise there is no way to convert a string to a long long int.

David Hammen
  • 32,454
  • 9
  • 60
  • 108