Correct format specifier for return value of sizeof() in C

前端 未结 3 1451
青春惊慌失措
青春惊慌失措 2020-11-30 10:53

I have the following code:

#include

int main()
{
    printf(\"The \'int\' datatype is \\t\\t %lu bytes\\n\", sizeof(int));
    printf(\"The \         


        
相关标签:
3条回答
  • 2020-11-30 11:09

    You're trying to print the return value of sizeof operator, which is usually of type size_t.

    It appears, in your case, size_t is a typedef of long unsigned int, so it demands it's compatible format specifier %lu to be used. The returned value here does not matter, your problem is with the type mismatch.

    Note: To have a portable code, it's safe to use %zu, on compilers based on C99 and forward standards.

    0 讨论(0)
  • 2020-11-30 11:11

    In C the type of a sizeof expression is size_t.

    The printf specifier to use is %zu. Example:

    printf("The 'int' datatype is \t\t %zu bytes\n", sizeof(int));
    

    It has been possible to use this since the 1999 version of the C standard.

    0 讨论(0)
  • 2020-11-30 11:30

    Technically, you have undefined behaviour due to mismatched format and data types.

    You should use %zu for the type associated with sizeof (which is size_t). For example:

     printf("The 'int' datatype is \t\t %zu bytes\n", sizeof(int));
    

    This is particularly important if you intend to target both 32 and 64 bit platforms.

    Reference: http://en.cppreference.com/w/c/io/fprintf

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