I'm a newbie. Is this code ugly?

C

Christopher Dearlove

Richard Herring said:
So you're using wrapping as a poor substitute for checking that t is in
range. On most systems, t will reach a value which exceeds the available
memory long before it wraps to a negative value.

And, while it usually happens to work, wrapping of signed integers
is actually undefined behaviour.

If you are using unsigned integers (like size_t) it's easy to check wrapping
of addition (although as noted that probably is the wrong test). If a, b, c
are such values and

c = a + b;

Then wrapping has ocurred if (and only if) c < a (or, equally well, c < b).

What I don't know how to do without using division - any solutions welcome
- is to check the overflow of a * b (unsigned again). c = a * b can overflow
but with c > a and c > b. That's not the issue here, but it's one I have
wanted
(for smaller unsigned types than size_t).

Of course with regard to the original code this is nit-picking fine points
of code that the only thing to actually do with it is bin it and start
again.
It's instructive that the poster has had to revise the code at least twice
since posting to fix bugs. The polite term is unmaintainable.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top