Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this code doing? (size_t)-1

Tags:

c++

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
like image 466
jterm Avatar asked Oct 07 '13 20:10

jterm


People also ask

What exactly is size_t?

size_t type is a base unsigned integer type of C/C++ language. It is the type of the result returned by sizeof operator. The type's size is chosen so that it can store the maximum size of a theoretically possible array of any type. On a 32-bit system size_t will take 32 bits, on a 64-bit one 64 bits.

What is meant by size_t in C++?

size_t is an unsigned integral data type which is defined in various header files such as: <stddef.h>, <stdio.h>, <stdlib.h>, <string.h>, < time .h>, <wchar.h> It's a type which is used to represent the size of objects in bytes and is therefore used as the return type by the sizeof operator.

Can a size_t be negative?

The size_t datatype in C/C++ Essentially, size_t is an unsigned datatype. This means that it can't be negative.

Is size_t signed C++?

Yes, size_t is guaranteed to be an unsigned type.


2 Answers

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.

like image 100
sasha.sochka Avatar answered Oct 09 '22 08:10

sasha.sochka


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

See also the following question c cast syntax styles

like image 32
Rod Avatar answered Oct 09 '22 10:10

Rod