12

Can someone explain what happens when size_t, or any other type identifier, is wrapped in parentheses. I know it is the old typecast syntax but in this context I don't follow what is happening.

I've seen it for defining the max size of a type as:

size_t max_size = (size_t)-1
jterm
  • 973
  • 1
  • 12
  • 32

4 Answers4

17

This code (unnecessarily) casts -1 to size_t. The most probable intent was getting the largest possible value of size_t on this system.

Although this code doesn't have Undefined Behavior, this code is ugly - in C++ you should use std::numeric_limits<size_t>::max() and in C use SIZE_MAX macro for exactly a purpose of getting the largest size_t value.

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
sasha.sochka
  • 14,395
  • 10
  • 44
  • 68
  • 3
    This code has well-defined behaviour. You might not like it, but it's sanctioned by the standard. (Both C and C++ standards, in fact.) And in C++ (the OP tag), you should use `std::numeric_limits::max()` – rici Oct 08 '13 at 01:10
1

(size_t)-1 is in fact the equivalent of size_t(-1)

See also the following question c cast syntax styles

Community
  • 1
  • 1
Rod
  • 52,748
  • 3
  • 38
  • 55
0

Some library methods intentionally return (size_t)(-1) to indicate an error condition. For example, the iconv method from the GNU libiconv library. I assume there is some good reason why these functions don't return ssize_t (signed) return values, which would allow you to check for -1 directly.

MikeOnline
  • 994
  • 11
  • 18
  • You wouldn't want to dedicate 16 bit only for the negative error codes. –  Sep 09 '19 at 14:39
0

for one of the code snippet I have encountered, size_t-1 aimed simply to have -1. They wanted to terminate for negative values.

The code snippet is bellow.

while (len != (size_t)-1) 
{
    mod = num % 16;
    if (mod < 10)
        str[len] = mod + '0';
    else if (mod >= 10)
        str[len] = (mod - 10) + 'a';
    num = num / 16;
    len--;
}
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 28 '23 at 00:53