3

I'm attempting to parse a text file backwards. I have the parsing done, now I'm trying to give my function a limit so that it doesn't read my entire 5Mb-2Gb log file. I'm passing this limit as a size_t and I was trying to think of a way to default the limit to read everything in the file.

since passing -1 to an unsigned type will set the highest bit, I'm assuming this will mean I get the max size of size_t. I was wondering, is this bad form? Also, is there a better way to accomplish my goal.

AlexLordThorsen
  • 8,057
  • 5
  • 48
  • 103

2 Answers2

5

In order to get the maximum possible value a size_t can hold, use std::numeric_limits. This would be the most portable way to do it:

#include <limits>

size_t max_value = std::numeric_limits<size_t>::max();
mfontanini
  • 21,410
  • 4
  • 65
  • 73
  • +1. This has the added bonus that it's obvious to everyone, as opposed to the `-1` trick. Although `-1` will do what you want, it requires casting or disabling useful compiler warnings, and will not be obvious to many programmers. – Adrian McCarthy Aug 22 '12 at 23:39
3

In regards to the question on whether it is "okay" to use -1 to get the max size of a unsigned integral type, I will refer you to this question/answer here.

Given that answer, an additional option you have available that follow a better C++ methodology would be to use std::numeric_limits<size_t>::max().

Finally, in C you could use one of the various _MAX definitions in limits.h that describe the maximum integral value for the data-type you're reading. For example, with a size_t type, you would use SIZE_MAX, etc.

Community
  • 1
  • 1
Jason
  • 31,834
  • 7
  • 59
  • 78
  • 4
    `-1` will always give the largest value for any unsigned type. The arithmetic for unsigned types is made like this. Also, there is a macro for `size_t`: `SIZE_MAX` – Jens Gustedt Aug 22 '12 at 21:56
  • My understanding is that for one's compliment, the negative of 0x0001 would only be 0xFFFE, which is not the largest unsigned value. – Jason Aug 22 '12 at 22:15
  • 2
    @jason - a negative value cannot be represented by any unsigned type, so the conversion requirement will kick in. That requirement kicks in based on the value, not based on the bits representing the value. – Michael Burr Aug 22 '12 at 22:17
  • @MichaelBurr Okay, I see what's going on from the answer here: http://stackoverflow.com/questions/50605/signed-to-unsigned-conversion-in-c-is-it-always-safe ... Thanks for not punishing me too hard :-) – Jason Aug 22 '12 at 22:26
  • I wouldn't call the referenced question "excellent". The long list of answers, many of which are contradictory, suggests that it's a controversial practice. Besides, that question was about setting all bits in a bitfield, which is different in _intent_ than this question, making it not a great reference. – Adrian McCarthy Aug 22 '12 at 23:43