我有一个简单的c ++方法,可在cout上打印Ascii字符0 = 255。这里是 :
void print_ascii()
{
unsigned char c = 0;
while (c < 255)
{
cout << c << endl;
c = c+1;
}
}// end print_ascii()
int main()
{
print_ascii();
}
上面的代码工作正常,但是当我尝试使用char时却溢出了char(c
我的问题是,由于有时很难记住类型的上限,如何针对这些情况(offbyone)抛出异常?
最佳答案
溢出通常不会对整数“起作用”,并且肯定unsigned char
会自动环绕。
您可以执行以下操作:
while (c <= 255)
{
cout << c << endl;
int temp = c + 1;
if (temp > 255) throw whatever_excpetion;
c = t;
}
关于c++ - 如何抛出C++异常超出范围,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14491981/