3.2 exceed.cpp

3.2 exceed.cpp

1 程序清单 3.2

  1. exceed.cpp

    // exceed.cpp --exceeding some integer limits
    
    #include <iostream>
    #include <limits>
    
    #define ZERO 0   // makes ZERO symbol for 0 value
    
    int main()
    {
        using namespace std;
        short sam = SHRT_MAX;  // initialize a variable to max value
        unsigned short sue = sam; // okay if variable sam already defined
    
        cout << "Sam has " << sam << " dollars and Sue has " << sue;
        cout << "dollars deposited." << endl
             << "Add $1 to each account." << endl << "Now ";
        sam = sam + 1;
        sue = sue + 1;
        cout << "Sam has " << sam << " dollars and Sue has " << sue;
        cout << " dollars deposited.\nPoor Sam!" << endl;
    
        sam = ZERO;
        sue = ZERO;
        cout << "Sam has " << sam << " dollars and Sue has " << sue;
        cout << " dollars deposited." << endl;
        cout << "Take $1 from each account." << endl << "Now ";
        
        sam = sam - 1;
        sue = sue - 1;
        cout << "Sam has " << sam << " dollars and Sue has " << sue;
        cout << " dollars deposited." << endl << "Lucky Sue!" << endl;
    
        return 0;
    }
    
  2. 运行结果

    Sam has 32767 dollars and Sue has 32767dollars deposited.
    Add $1 to each account.
    Now Sam has -32768 dollars and Sue has 32768 dollars deposited.
    Poor Sam!
    Sam has 0 dollars and Sue has 0 dollars deposited.
    Take $1 from each account.
    Now Sam has -1 dollars and Sue has 65535 dollars deposited.
    Lucky Sue!
    

2 说明

  1. 以上结果输出来自运行64位Windows7 系统。

  2. 典型的整型溢出行为

    3.1

posted @ 2022-01-17 23:44  kaizenly  阅读(55)  评论(0编辑  收藏  举报
打赏