Reputation: 3082
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;
}
Upvotes: 3
Views: 2179
Reputation: 263118
If for some reason you don't want to include a header, you can let C++ infer the correct type:
decltype(sizeof(0)) n;
Upvotes: 1
Reputation: 20063
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.
Upvotes: 1