SREG and arithmetic overflow

Hi all,

I want to handle signed integer arithmetic lightning fast (32 bit signed integer) and have tried accessing SREG but it always reads zero. So something is in the way. I'm just wondering if anyone has a solved this.

Basically I just want this to work:

etc...
C = A + B; //overflow event
my_sreg = SREG;

Is the failure a compiler option thing?
Is there a single bit of inline assembler that would guarantee I got SREG?

confused.

cheers
colin

I've just tried Serial.println(SREG,HEX) on a NANO and it prints 82 which means that global interrupts are enabled (80) and the Zero result flag is set.
Which Arduino are you using?

I want to handle signed integer arithmetic lightning fast

Why do you think that what you're trying to do will be so much faster than what the compiler uses?

Pete

You can fetch SREG, but with compiler optimization and code reordering and all that, there is no guarantee that its contents will have anything to do with the last arithmetic expression that was in your source code. C (the language) has “undefined” behavior in the presence of integer overflow; this is one of the few areas where you can occasionally write assembly language that out-preforms C code. But you have to write the whole expression sequence in assembly…

Thanks el_supremo and westfw,

You've basically confirmed my expectations.

I don't really want an Assembly and/or Makefile UNO odyssey just now. Life is short and tricky enough! I guess I'll just have to do my own integer prechecks. It's a research context and I can accommodate the delays in the short term. I just thought someone might have sorted it already. Oh well...

Thanks for the heads up!

cheers
colin

You can do the math in a one-step larger integer size and check the resulting high byte; that's how common things that rely on carry (ie TCP ones-complement checksum) tend to be implemented:

  uint16_t a,b, sum;
  uint32_t intermediate;
  boolean overflow;
  intermediate = ((uint32_t)a + b);
  overflow = (intermediate & 0xFFFF0000) != 0;
  sum = intermediate;

I don't know how well gcc will optimize that for you; you can re-arrange and experiment...
Note that technically "sum = a+b" is undefined if an overflow occurs.