如何检测C ++中的溢出? [英] How to detect an overflow in C++?

查看:142
本文介绍了如何检测C ++中的溢出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道是否有一些方便的方法来检测运行时C ++程序中使用的任何缺省数据类型的变量是否发生溢出?通过方便,我的意思是,如果每次变量的值在其数据类型范围内,都不需要编写代码来跟踪每个变量。或者如果这是不可能的,你会怎么做?

I just wonder if there is some convenient way to detect if overflow happens to any variable of any default data type used in a C++ program during runtime? By convenient, I mean no need to write code to follow each variable if it is in the range of its data type every time its value changes. Or if it is impossible to achieve this, how would you do?

例如,

For example,

float f1=FLT_MAX+1;
cout << f1 << endl;

在编译gcc -W -Wall或运行时不会给出任何错误或警告。

doesn't give any error or warning in either compilation with "gcc -W -Wall" or running.

感谢和问候!

推荐答案

考虑使用促进数字转换,它可以让你 negative_overflow positive_overflow 例外( examples )。

Consider using boosts numeric conversion which gives you negative_overflow and positive_overflow exceptions (examples).

这篇关于如何检测C ++中的溢出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆