使用C或C++时,如何防止整数溢出

How do I prevent integer overflow when using C or C++?

本文关键字:何防止 整数 溢出 C++ 使用      更新时间:2023-10-16

http://ideone.com/hANuZ

#include <stdio.h>
int main(int argc, char *argv[]) {
    /**
     * Prints out powers of 2 for 32 iterations.
     */
    int iterations = 0;
    int value = 1;
    while (iterations <= 32) {
        // Prints in this format: iterations    2^n    value
        printf("%dt2^%dt%d", iterations, iterations, value);
        switch (iterations) {
          case 8:
          case 16:
          case 32:
              printf("tt%d bitn", iterations);
              break;
          default:
              printf("n");
              break;
        }
      value *= 2;
      ++iterations;
    }
    return 0;
}

当我编译并运行这段代码时,当我在"value"大于2^30之后打印它时,即使我将其声明为无符号长时,也会发生奇怪的事情。

我该怎么办?我只是个初学者-(

您将其打印为带符号整数。尝试使用格式字符串

"%ut2^%ut%u"

检查您的printf文档中的所有格式化代码及其作用。%u代表unsigned intunsigned long通常是%lu

简单的答案是尝试将其声明为大于32位的unsigned long long(根据标准,thx@caf,最小为64位(。

当处理特定大小很重要的类型时,应该使用已知大小的类型,如int64_t

只是为了好玩,我确实修改了您的代码示例以提高的清晰度

#include <stdio.h>
int bitcount(unsigned long i) {
   int count = 0;
   while (i > 0) {
      count++;
      i>>=1;
   }
   return count;
}
int main(int argc, char *argv[]) {
   /**
    * Prints out powers of 2 for 32 iterations.
    */
   int iterations = 0;
   int value = 1;
   while (iterations <= 32) {
      // Prints in this format: iterations    2^n    value
      printf("%dt2^%ut%utt%d bitn", iterations+1, iterations, value, bitcount(value));
      value *= 2;
      ++iterations;
   }
   return 0;
}

您会注意到1278 bit2569 bit。这是因为

127 =   1000 0000
256 = 1 0000 0000

此外,2^320,因为

2^32 = 1 0000 0000 ... 0000 0000       (overflow for int)
     =   0000 0000 ... 0000 0000 = 0   (only the first 32 bits are preserved)

如果需要整数精度,则需要使用外部库来获取较大的数字。对于C GMPhttp://gmplib.org/是一个著名的图书馆。如果不需要整数精度,只需使用浮点或双精度。

如果你想知道类型的限制是基于什么,这个页面是可以阅读的http://www.lix.polytechnique.fr/~liberti/public/computing/prog/c/CONCEPT/data_types.html.