0

I'm wondering if it is allowed in C++ to use overflow on purpose. In specific I want to increase a counter every cycle and when uint32_max is reached start from 0.

In my mind the easy way would be:

uint32_t counter = 0;
while(condition)
{
    counter++;
    ...
}

or would you manually reset the counter?:

uint32_t counter = 0;
while(condition)
{
    if(counter == uint32_max)
    {
        counter = 0;
    }
    else
    {
        counter++;
    }
    ...
}
3
  • 2
    Yes it's OK. Such "overflow" of unsigned integral values is well defined and behaves like you expect - i.e. wraps to 0 (this is not true for signed values though). Commented Nov 29, 2024 at 13:48
  • 3
    For standard unsigned integral types, it is fine to use overflow "on purpose", since the behaviour on overflow is well-defined by the C++ standard. For other types (e.g. signed integral types, floating point types) that is not true. Commented Nov 29, 2024 at 14:01
  • "on purpose" --What C++ allows and what it does not allow does not depend on the intent of the programmer. Better would be to ask if you can use overflow to reset a counter (i.e. if your desired behavior is guaranteed by the standard). Commented Nov 29, 2024 at 15:37

1 Answer 1

4

That is fine because you used uint32_t. Unsigned integers do not overflow but wrap-around from the maximum value to zero. Such behavior is well-defined in C++, unlike signed integer overflow/underflow.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.