Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gcc: division by zero

I am getting division by zero error at this line:

if (tim2_st_ovf < T2_PREK_250)

These values are defines like this:

volatile uint8_t tim2_st_ovf = 0;

#define T2_PREK_250    ((250 * (F_CPU / 1000)) / ((UINT8_MAX + 1) * 1024))
#define F_CPU    16000000UL

And UINT8_MAX equals to 255.

Why am I getting this? I calculated it several times on calculator and am getting ~15. Also, if I change 1024 to 1023 it doesnt show any error.

like image 260
user1806687 Avatar asked Sep 06 '14 16:09

user1806687


People also ask

Can you divide by 0 in C?

In languages like C, C++ etc. division by zero invokes undefined behaviour. So according to the language definition, anything can happen.

Does C++ allow you to divide by 0?

Handling the Divide by Zero Exception in C++Dividing a number by Zero is a mathematical error (not defined) and we can use exception handling to gracefully overcome such operations.

Is NaN division by zero?

Dividing a floating-point value by zero doesn't throw an exception; it results in positive infinity, negative infinity, or not a number (NaN), according to the rules of IEEE 754 arithmetic.


1 Answers

((UINT8_MAX + 1) * 1024) may become 0, because UINT8_MAX + 1 is usually 256, and 256 * 1024 is 0 modulo 216. So if sizeof(int) == 2 on your achitecture, then you get 0.

On the typical modern desktop architectures with GCC, sizeof(int) == 4, and you wouldn't get the division by 0.

To fix it, replace 1024 with 1024UL. That will work, because unsigned long is guaranteed to go up to 4294967295. (Thanks to Pascal Cuoq for explaining it.)

like image 113
pts Avatar answered Oct 01 '22 14:10

pts