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

前端 未结 3 1467
青春惊慌失措
青春惊慌失措 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: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

提交回复
热议问题