Before the program crashes, that is.. I have no clue how to do this. I'm adding values to a variable and I want to check before it overflows.
Before the program crashes, that is.. I have no clue how to do this. I'm adding values to a variable and I want to check before it overflows.
The simplest is probably to compare your variable to INT_MAX, defined in limits.h.
So, something like this: if( var < INT_MAX )
test if current value < last value
Quzah.Code:if( valuetoadd > maximumvalue - currentvalue ) ...boo else ...yay
Hope is the first step on the road to disappointment.
thanks for your answers, gentlemen. This will help me.
Odd as it may seem... this is probably the only reliable test you have... see if it rolled over the top.
An integer will never be > INT_MAX ... as itCbitC points out it will roll back over to 0 or -1 first.
Assuming 32 bits...
Code:int a = 2147483645; a = a + 3; printf("%d",a); // - 1 unsigned int b = 4294967293; b = b + 3; printf("%d",b); // 1
Last edited by CommonTater; 03-17-2011 at 11:13 PM.
Which only works if val and value_to_add are 32 bits.
Back in the good old Pascal days everyone was wondering how TP detected overflows at run time when in-code solutions like these failed so miserably. The answer turned out to be quite simple... The overflow flag in the CPU... a little bit of assembler at the end of each math function would check the OF flag, if it was lit up, the program tossed an exception.
http://en.wikipedia.org/wiki/FLAGS_register_(computing)
A similar process could probably be implemented in C, but it would most likely mean rewriting very large parts of everything to make it work...
You might try...
Code:if ((INT_MAX - current_value) > value_to_add) current_value += value_to_add else DoTheMassivelyAnnoyingErrorThing();
Last edited by CommonTater; 03-18-2011 at 09:29 AM.
Of course but the question was about ints, otherwise you would not use INT_MAX, but really quazah's method works no matter what. And checking the overflow flag is a bit overkill I think, it's only set after the fact, so you would need to create a test function specific for addition and ints, something like this.
Code:int overflow_add(int a, int b) { int test = a + b; int ofl = 0; __asm__( "seto %b0;" : "=g"(ofl) : : "%bh" ); return ofl; }
Obviously, it's already been posted and agreed upon.
Last edited by Subsonics; 03-18-2011 at 10:05 AM.
Of course mine will, it will also work for self-imposed limits:Unless you are talking about negative numbers, and going lower instead of going higher as you check for limits, but then all you do is change 'max' to 'min', and > to < and + to - ... which while easy enough to do, isn't what he asked for.Code:if( 300(add) > 1000(max) - 800(current) ) boo else yay
Don't just tell me it doesn't work, show me how it doesn't work, because I'm not seeing it.
Quzah.
Hope is the first step on the road to disappointment.