0

I am doing some calculation with increment as below.

DOUBLE result;
UINT32 data;

while(1)
{
    result = data + 1;
}

But when data=0xFFFFFFFF(4 byte max value), result becomes 0 by doing above calculation.

I guess a data overflow occured.

So I wonder if there is any way I can do this calculation continuously without changing data type of ‘data’ to bigger size.

porpomas
  • 41
  • 4
  • `data + 1` is an integer operation with an integer result. Even though `result` could hold larger values, the value assigned to it will already have had the overflow. – Some programmer dude Aug 17 '22 at 10:20
  • The example is sketchy. `1.0 * data + 1` buys you a bit more time (up to the 53rd power of 2 for IEEE754 `double`). – Bathsheba Aug 17 '22 at 10:21
  • You shouldn't make up your own, home-made type systems. There exists no reason why you shouldn't be using `double` and `uint32_t` instead of your local garage type standard. – Lundin Aug 17 '22 at 10:42
  • 1
    Re “this calculation”: You have not told us what “this calculation” is. You have shown just fragments from some other code and left out things necessary to figure out what result you actually want. You did not show how `result` or `data` are initialized or explained what you want in `data` over time or what you want in `result`. – Eric Postpischil Aug 17 '22 at 12:14
  • @porpomas `while(1) { result = data + 1; }` --> `result = data; while(1) { ++result; }` should keep it looping and incrementing for a _long_ time. – chux - Reinstate Monica Aug 17 '22 at 13:06

1 Answers1

0

Calculations in C are carried out on the type obtained from the operands of an operator, not based on the type of whatever variable you decide to store the result inside.

In your example data is supposedly uint32_t and the integer constant 1 is of type int. The usual arithmetic conversions (see Implicit type promotion rules) converts the int to a uint32_t, then the + is carried out on two operands with that type.

Wrap-around is well-defined for unsigned types, so 0xFFFFFFFF + 1 becomes zero. If you wished for the result 0x100000000 instead, you need to ensure that both operands of + are of type uint64_t or perhaps double.

Lundin
  • 195,001
  • 40
  • 254
  • 396