繁体   English   中英

如何抛出C ++异常超出范围

[英]How to throw a c++ exception for out of range

我有一个简单的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 <= 255),因为它超出了unsigned char符号。

我的问题是如何针对这些情况( offbyone )抛出异常,因为有时很难记住类型的上限?

溢出通常不会对整数“起作用”,当然, unsigned char只会环绕。

您可以执行以下操作:

while (c <= 255)
{
    cout << c << endl;
    int temp = c + 1;
    if (temp > 255) throw whatever_excpetion;
    c = t;
}

如前所述,溢出后未签名的聊天将为0。 您可以在此期间使用它

unsigned char x = 0;
do{
     code;
     ++x;
} while (x!=0);

但我不确定它是否易于阅读。 天真的一个:

for (c = 0;true;++c){
     code;
     if (c == numeric_limits <unsigned char>:: max ()) break;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM