Click here to Skip to main content
15,911,315 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi guys,

Can any one help me with detecting an overflow with data type long. I C++.
i dont want to go for the arithmetic way that if b < (b+C) then over flow occurred.
Is there any Method or falg that will detect the overflow for me.?

With Regards,
Saurabh
Posted

Idle63 posted a good answer for an alternative to a 'long' data type.

But a more direct answer is that, there is no method or flag, built into the C language that will detect this overflow for you.

The C language was designed to operate as close to the metal as possible. Widespread bounds validation for primitive types, would severely impact code performance, and is left as an exercise for the software engineer. Further, customization of bounds checking, requires additional variables to compare against, for underflow and overflow. This would add additional complexity to primitive data types.
 
Share this answer
 
Comments
Vitaly Tomilov 20-Jun-12 13:11pm    
Inline assembler inserts are widely supported, which gives you direct access to the overflow flag.
JackDingler 20-Jun-12 13:21pm    
If your processor supports integer overflow flags, then this is correct.

I'm not sure how your comment relates to mine though.
1. If you understand assembler, then you can use operands JO and JNO to jump when overflow flag is set or not, accordingly. This would be the universal answer on x86 platform.

2. If you do not understand assembler, then just use safe types like Safe Integer - see them used in MSDN.
 
Share this answer
 
You can use SafeInt. http://msdn.microsoft.com/en-us/library/dd570023(VS.100).aspx[^]

But probably it perfromance goes down.
Regards
 
Share this answer
 
Comments
JackDingler 18-Jun-12 12:46pm    
Good answer. and of course performance will be effected, much like the test b < (b+C), which is likely built into the SafeInt template in some form.
[no name] 18-Jun-12 14:52pm    
Thx. Yes I would also prefer "test b < (b+C)".
Regards.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900