AlexLordThorsen
AlexLordThorsen

Reputation: 8498

proper form with size_t (passing -1 as a default value to get max size)

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.

Upvotes: 3

Views: 1905

Answers (2)

Jason
Jason

Reputation: 32520

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.

Upvotes: 3

mfontanini
mfontanini

Reputation: 21900

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();

Upvotes: 5

Related Questions