What does a type followed by _t (underscore-t) represent?

后端 未结 10 578
萌比男神i
萌比男神i 2020-11-22 07:15

This seems like a simple question, but I can\'t find it with the Stack Overflow search or Google. What does a type followed by a _t mean? Such as



        
相关标签:
10条回答
  • 2020-11-22 07:49

    As Douglas Mayle noted, it basically denotes a type name. Consequently, you would be ill-advised to end variable or function names with '_t' since it could cause some confusion. As well as size_t, the C89 standard defines wchar_t, off_t, ptrdiff_t, and probably some others I've forgotten. The C99 standard defines a lot of extra types, such as uintptr_t, intmax_t, int8_t, uint_least16_t, uint_fast32_t, and so on. These new types are formally defined in <stdint.h> but most often you will use <inttypes.h> which (unusually for standard C headers) includes <stdint.h>. It (<inttypes.h>) also defines macros for use with the printf() and scanf().

    As Matt Curtis noted, there is no significance to the compiler in the suffix; it is a human-oriented convention.

    However, you should also note that POSIX defines a lot of extra type names ending in '_t', and reserves the suffix for the implementation. That means that if you are working on POSIX-related systems, defining your own type names with the convention is ill-advised. The system I work on has done it (for more than 20 years); we regularly get tripped up by systems defining types with the same name as we define.

    0 讨论(0)
  • 2020-11-22 07:49

    There were a few good explanations about the subject. Just to add another reason for re-defining the types:

    In many embedded projects, all types are redefined to correctly state the given sizing to the types and to improve portability across different platforms (i.e hardware types compilers).

    Another reason will be to make your code portable across different OSs and to avoid collisions with existing types in the OS that you are integrating in your code. For this, usually a unique (as possible) prefix is added.

    Example:

    typedef unsigned long dc_uint32_t;
    
    0 讨论(0)
  • 2020-11-22 07:50

    For example in C99, /usr/include/stdint.h:

    typedef unsigned char           uint8_t;
    typedef unsigned short int      uint16_t;
    #ifndef __uint32_t_defined
    typedef unsigned int            uint32_t;
    # define __uint32_t_defined
    #endif
    #if __WORDSIZE == 64
    typedef unsigned long int       uint64_t;
    #else
    __extension__
    typedef unsigned long long int  uint64_t;
    #endif
    

    _t always means defined by typedef.

    0 讨论(0)
  • 2020-11-22 07:53

    It's just a convention which means "type". It means nothing special to the compiler.

    0 讨论(0)
提交回复
热议问题