How we use standard exception(in c++) ,overflow of int data type ? | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
+ 1

How we use standard exception(in c++) ,overflow of int data type ?

Suppose i have the following code: int a=1234234234; //a is not in range of integer data-type which cause warning //how we use standard exception in in the above case. // plz write a small exception handling code

12th May 2021, 4:48 AM
𝖆𝖙.𝖚𝕷
𝖆𝖙.𝖚𝕷 - avatar
4 Respuestas
+ 3
If the number is too large and you see a warning, you don't need code to fix the problem. Just change it to `long` or a smaller number. The number you wrote there will never change unless you change it, and then compile again. You don't need code that checks at runtime if the number is too large, since the error will already be caught at compile time. The "exception handling" is you, the prgrammer, fixing the problem in code.
12th May 2021, 8:25 AM
Schindlabua
Schindlabua - avatar
+ 2
Just use initializer lists for initialization instead of the assignment operator. `int a{ 12345654321 };` The above line gives a compile time error. This however will only work when you're initializing the variable. For the other cases, you can refer to this https://www.embeddedrelated.com/showarticle/532.php (Side note: the number in your question is a valid integer and does not give warning)
12th May 2021, 4:57 AM
XXX
XXX - avatar
+ 2
Well yeah and the exception happens at compile time, so runtime checks are unneccessary. If you are talking about overflow in general, like, how do you know whether `a+b` overflowed, given large numbers `a` and `b`, there is no easy answer. For `c = a+b` you could check whether `c < a || c < b`, if you know that both numbers are positive. If true, you know an overflow occurred. But this check already fails for multiplication. Some CPUs have an overflow register that is set to 1 whenever an overflow happens, but there is no real way to read it's value in C++ and then again, some CPUs don't even have one. In any case, overflows in C++ don't produce exceptions and usually you won't know it happened until your program produces garbage output. If you know you will be using large numbers in your code and may run the risk of overflowing, you should switch to longs, or doubles, or even bigints that can hold arbitrarily large numbers.
12th May 2021, 1:14 PM
Schindlabua
Schindlabua - avatar
0
Guys, the main topic is exception handling in this case
12th May 2021, 9:37 AM
𝖆𝖙.𝖚𝕷
𝖆𝖙.𝖚𝕷 - avatar