Does it matter which header (cstddef, cstdio, cstdlib, etc.) I include to get the definition of size_t?

876 Views Asked by At

According to http://en.cppreference.com/w/cpp/types/size_t , the type size_t is defined in many header files: cstddef, cstdio, cstdlib, etc.

While writing my own code which header file should I include to use size_t?

This might seem like a trivial question, but as a beginning of C++ I am concerned about the following:

  • Can I include any header file and be sure that size_t would behave in the same way regardless of which header file I included?
  • Are there any surprises I need to be aware of like including one header file would have surprising side-effects that including another header file would not have?
  • Is there a coding convention or popular convention or practice regarding this that leads to most people including a specific header file to get the definition of size_t?
2

There are 2 best solutions below

3
R Sahu On BEST ANSWER

Can I include any header file and be sure that size_t would behave in the same way regardless of which header file I included?

Yes.

Are there any surprises I need to be aware of like including one header file would have surprising side-effects that including another header file would not have?

No.

Is there a coding convention or popular convention or practice regarding this that leads to most people including a specific header file to get the definition of size_t?

I personally prefer <cstddef> but I am not aware of any conventions.

2
101010 On

Is there a coding convention or popular convention or practice regarding this that leads to most people including a specific header file to get the definition of size_t?

No, there's not or at least none that popular that I know of. Personally, in cases where I only need std::size_t, in order not to drag unnecessary code from the headers that define std::size_t, I define my own size_t as:

using size_t = decltype(sizeof(char));

Note: The above also complies with the standard definition of std::size_t.