What does this code do? (Size_t) -1

Can anyone explain what happens when size_t or any other type identifier is enclosed in parentheses. I know this is the old typecast syntax, but in this context I do not follow what happens.

I saw it to determine the maximum type size:

size_t max_size = (size_t)-1 
+8
source share
3 answers

This code is (redundant) -1 to -1 in size_t . The most likely intention was to get the maximum possible size_t value in this system.

Although this code does not have undefined behavior, this code is ugly - in C ++ you should use std::numeric_limits<size_t>::max() and in C use the SIZE_MAX macro just for the purpose of getting the largest size_t value,

+10
source

(size_t)-1 actually equivalent to size_t(-1)

See also the following question on cast syntax styles.

+1
source

Some library methods intentionally return (size_t)(-1) to indicate an error condition. For example, the iconv method from the GNU libconv library . I assume there is a good reason why these functions do not return ssize_t (signed) return values, which allows you to directly check -1.

0
source

Source: https://habr.com/ru/post/955444/


All Articles