3 ms·
Say you're comparing the number of views between two different videos as (video_A.views - video_B.views). How do you represent that the second video has more vi
by spb 12y ago
Say you're comparing the number of views between two different videos as (video_A.views - video_B.views). How do you represent that the second video has more views than the first?
- nly 12y agovideo_B.views > video_A.views
- tempestn 12y agoAnd what if you want to say how many more? You'd have to first check which one is greater, and then subtract in the right direction. The code is simpler if you just use signed integers.
- vegedor 12y agoYou could still typecast. The code may be simpler, but less explicit. In a storage heavy application it's still sensible to save bytes. Even if it is not a remarkable saving in this case, especially with compression algorithms reducing the impact. Assert will stop the program immediately, so you want to sensibly catch the error, at which point you need to know as much about the error condition as you need to know to use unsigned or casts correctly. So it's rather a question of taste, isn't it?
- bobbykjack 12y agoTo say "b has n more views than a", you need two operations whether you use signed or unsigned ints. Signed let's you say "these two videos have n different views" but, to be honest, it seems unlikely that you be doing either in so many places in your codebase, or so frequently during execution, to make the extra operation that significant.
- tempestn 12y agoYes, in this specific example you still need the same number of operations. My point was, when you just use signed integers, it's easier to conceptualize and harder to screw up. It's more flexible for unforeseen future use cases. Also, this is a very simplified example case; in most scenarios those unforeseen possibilities will be more significant. Given that switching to unsigned saves you exactly one bit, it's just not usually worth it. How often do you need exactly 32 bits of unsigned space, when 31 isn't enough, and you can't use 63? (I'm talking about standard-length integers here, not extreme situations where you're trying to make maximum use of 8 bits of storage or similar.)