Fork me on GitHub

范围不相符变量的赋值

  当超出某一类型范围的值给此类型变量赋值或某一负数给某一无符号数赋值时,其结果会怎么样呢?

(1)超出某一类型范围的值给此类型变量赋值时

    变量的值 = 超出某一类型范围的值 % 此类型可以表示的数值的个数

  例:char a = 260 ; 输出 a = 4 ;

#include "stdafx.h"
#include<iostream>
#include<iomanip>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    char a=260;
    cout<<(int)a<<endl;

    system("pause");
    return 0;
}

(2)某一负数给某一无符号数赋值时

    无符号变量的值 = (某一负数 % 此类型可以表示的数值的个数) + 此类型可以表示的数值的个数

  例:unsigned char a = -2 ; 输出 a = 254 ;

#include "stdafx.h"
#include<iostream>
#include<iomanip>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    unsigned char a=-2;
    cout<<(int)a<<endl;

    system("pause");
    return 0;
}

参考链接:

  http://www.cnblogs.com/volcanol/p/3987121.html

posted @ 2015-08-10 11:27  晨光iABC  阅读(293)  评论(0编辑  收藏  举报