4

I have recently been told that using size_t as declared in the global namespace is incorrect in C++, ostensibly because size_t is a C-feature. I looked this up and came across this question on Stack Overflow:

https://stackoverflow.com/questions/5813700/difference-between-size-t-and-stdsize-t

The top answer makes it pretty clear that there isn't any real difference between size_t and std::size_t, but that leaves open the question of style and correctness.

Since I'm programming in C++, is it "wrong" to use a C feature such as size_t in place of the slightly longer but no better C++-specific std::size_t?

  • I never write std::size_t fwiw. – Thomas Eding Jul 14 '14 at 23:07
  • Every C function has an equivalent alias in the std namespace, but I'm yet to see any project that does consistent use the std:: prefix for C-library calls. – glampert Jul 15 '14 at 2:42
5

<stddef.h> is a 100% standard header file in C++, that provides the type ::size_t.

As a bonus it also is standard in C. Very nice if you're writing a header file for a library with a C-compatible interface, using #if __cplusplus / extern "C" {.

Note that the usual arguments about namespaces and naming collisions don't apply, as the Standard allows inclusion of any or all header files to introduce ::size_t.

The only time that using std::size_t is "better" than ::size_t is if you have not included <stddef.h> (perhaps you have #include <cstddef> instead).

  • 2
    <stddef.h> is a 100% standard header file in C++?? isn't anything with .h are c header? – Bryan Chen Jul 15 '14 at 3:32
  • 2
    @Bryan: It assuredly is part of the C++ Standard. Section D.5 says "For compatibility with the C standard library and the C Unicode TR, the C++ standard library provides the 26 C headers. Every C header, each of which has a name of the form name.h, behaves as if each name placed in the standard library namespace by the corresponding cname header is placed within the global namespace scope." – Ben Voigt Jul 15 '14 at 5:43
  • @BryanChen: C++ inherits a lot from C, including just about the complete standard library. – Bart van Ingen Schenau Jul 15 '14 at 6:28
  • 1
    @BenVoigt: Wouldn't that make cstddef the only 100% standard C++ header, and stddef.h something slightly less? Say 99.9%? – david.pfx Jul 15 '14 at 8:45
  • @david.pfx: No it wouldn't. That is a normative rule, not a note, footnote, or suggestion. C++ places different requirements on the content of stddef.h than C does. And it is required for every hosted implementation. – Ben Voigt Jul 15 '14 at 14:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.