This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

OVERFLOW

HI Can anyone tell me that


 unsigned char time;
 .....
 void interrupt_timer ( void ) interrupt 1
{
   time++;
}

The unsigned char is of 1 byte and has maximum value of 255. So what will happen when the time exceeds 255?

  • normally it rolls back to 0.

    Normally, but don't rely on it. Behavior on integer overflow is not specified in the C standard, so basically anything could happen.

  • It is considered politically incorrect to design current hardware with something else than two-complement integers of size 2^n so it is extremely likely that it will happen with most hardware produced the last 20 years.

    But special hardware can have a reason to behave similar to IEEE floating point, i.e. to "lock" into +Infinity or -Infinity, to let the software notice that the value is invalid instead of producing bogus computation results. Not as strong protection as IEEE fp where +/- Inf and NaN have special meaning for +, -, *, /, sqrt, ... too, but at least a possibility for the software to see that a specific input operand can't be trusted.

  • If there is ANY doubt about standards and the compliance thereof, just write a simple bit of assembler.

    After all, people on forums like this are always saying how important it is to keep them as short and as fast as possible.

  • Or write your source code so that it doesn't rely upon the "doubted" behaviour.

    But, yes - you always know exactly where you are with assembler!

  • just write a simple bit of assembler

    I don't know the C51 family, but when working with an ARM the OP's problem can be best addressed using the "S" flavor of ARM instructions so that the processor overflow, zero etc. flags in CPSR are updated if necessary.

  • "Behavior on integer overflow is not specified in the C standard, so basically anything could happen."

    Integer overflow behavior is specified in the C standard. Signed integer overflow is specified as "undefined behavior" and about unsigned integer overflow behavior, the standard says:

    "A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type."