Why do I get an "arithmetic overflow in constant expression" message?

There are many reasons why this warning may be produced when compiling with MPLAB® XC8. Here are a few examples that might help you understand why it occurs in your code.

Example 1

The most common code to trigger this warning is assignments to signed data types. For example:

As a signed 8-bit quantity, c can only be assigned values -128 to 127. The constant is equal to 255 and is outside this range.

In general, if you want a value that has all bits set, and you don't want to be specific about how many bits that is, write the code as e.g.

This will set all the bits of c.

Example 2

This code will emit the warning of "arithmetic overflow" when BEEP_TIME is assigned to bep.

This is because 8000000 is by default a long number, but 3200 and 64 aren't, so 64*3200 is evaluated to int length, and overflows. Use an L suffix to force long arithmetic in the expression above as:

Note the L appended to 64, this makes it a long number, and the evaluation of 64L*3200 will be done to a 32-bit length.

Example 3

The statement i == (sizeof(vec) - 1) will emit the warning “arithmetic overflow in constant expression”.

This is because the compiler treats the value "- 1" as "+ 0xFFFF" (with a 16-bit operand). The result of the sizeof operator is five. So the five is added to 0xFFFF which causes an overflow, and this is what the compiler warns about.

To avert the warning re-write the code as:

The x will be treated as one, and not 0xFFFF because it has been declared as an unsigned type.

© 2024 Microchip Technology, Inc.
Notice: ARM and Cortex are the registered trademarks of ARM Limited in the EU and other countries.
Information contained on this site regarding device applications and the like is provided only for your convenience and may be superseded by updates. It is your responsibility to ensure that your application meets with your specifications. MICROCHIP MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED, WRITTEN OR ORAL, STATUTORY OR OTHERWISE, RELATED TO THE INFORMATION, INCLUDING BUT NOT LIMITED TO ITS CONDITION, QUALITY, PERFORMANCE, MERCHANTABILITY OR FITNESS FOR PURPOSE. Microchip disclaims all liability arising from this information and its use. Use of Microchip devices in life support and/or safety applications is entirely at the buyer's risk, and the buyer agrees to defend, indemnify and hold harmless Microchip from any and all damages, claims, suits, or expenses resulting from such use. No licenses are conveyed, implicitly or otherwise, under any Microchip intellectual property rights.