Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does "std::size_t" make sense in C++?

Tags:

c++

size-t

In some code I've inherited, I see frequent use of size_t with the std namespace qualifier. For example:

std::size_t n = sizeof( long ); 

It compiles and runs fine, of course. But it seems like bad practice to me (perhaps carried over from C?).

Isn't it true that size_t is built into C++ and therefore in the global namespace? Is a header file include needed to use size_t in C++?

Another way to ask this question is, would the following program (with no includes) be expected to compile on all C++ compilers?

size_t foo() {     return sizeof( long ); } 
like image 575
jwfearn Avatar asked Oct 26 '08 01:10

jwfearn


People also ask

Should I use Size_t or std :: Size_t?

So yeah, both are same; the only difference is that C++ defines size_t in std namespace.

What does std :: Size_t mean?

std::size_t is the unsigned integer type of the result of the sizeof operator as well as the sizeof... operator and the alignof operator (since C++11). The bit width of std::size_t is not less than 16. (since C++11)

Where is std :: Size_t defined?

size_t is a base unsigned integer memsize-type defined in the standard library of C/C++ languages. This type is described in the header file stddef.

Is Size_t built in?

The name size_t essentially means "size type", and you will typically see this data type used to specify the size or length of things - like the length of a C string returned by the strlen() function, for example. This is not one of the "built-in" data types of C/C++.


1 Answers

There seems to be confusion among the stackoverflow crowd concerning this

::size_t is defined in the backward compatibility header stddef.h . It's been part of ANSI/ISO C and ISO C++ since their very beginning. Every C++ implementation has to ship with stddef.h (compatibility) and cstddef where only the latter defines std::size_t and not necessarily ::size_t. See Annex D of the C++ Standard.

like image 170
Johannes Schaub - litb Avatar answered Sep 19 '22 04:09

Johannes Schaub - litb