Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

My C is rusty, but won't this act... oddly... on integer overflow?

    size()     { return write - read; }
0 - UINT_MAX -1 = ?

[EDIT] Changed constant to reflect use of unsigned integers, which I forgot to specify initially.



Actually, this method counts on it.

What I find interesting are the trade-offs: machine vs explicit integer wrap-around and buffers with maximum ~size(int)/2 vs ~size(int).


Got it. Modular arithmetic was the term I was looking for to resolve this.

    (0 - (2^32 - 1)) % 2^32 = 1


In all examples, `read` and `write` are unsigned, and since they both are the same type, no integer conversions are performed, ergo no overflow.

PS. No wrap-around either, for different reasons.


> No wrap-around either, for different reasons.

You'll have to explain that to me, since I can't assign `x = 2^32` without wraparound when x is an unsigned 32 bit integer.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: