including header file for size_t returned by sizeof operator

2.1k Views Asked by At

Should I include header file with definition of size_t (e.g. cstddef or stddef.h) for using sizeof keyword, which returns that type?

For example:

//..no include

int main()
{
    size_t n;  //error: unknown type size_t
    sizeof(int);  //ok, but returned size_t type also undefined
    return 0;
}
2

There are 2 best solutions below

0
On BEST ANSWER

You only need to include cstddef or stddef.h if you need to explicitly use size_t (i.e. in a declaration or definition). It is not necessary if if all you want to do it determine the size of a specific type using sizeof. For example the following statements do not require that you include any header file to use sizeof in determine the size of a type.

int a = sizeof(foo);
if(sizeof(foo) == 12) {}

If you're looking specifically for information about sizeof I suggest you take a look at 5.3.3 ([expr.sizeof]) of the C++ Standard for more information.

2
On

If for some reason you don't want to include a header, you can let C++ infer the correct type:

decltype(sizeof(0)) n;