How sizeof operator works in C? [duplicate]

本秂侑毒 提交于 2020-01-11 13:19:54

问题


In this below code:

#include<stdio.h>
int main(void)
{
    printf("%d",sizeof(int));
    return 0;
}

When compiled on gcc (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4 compiler it gives warning:

format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat=] printf("%d",sizeof(int));

Why I am getting this warning? Is it that return type of sizeof is 'long unsigned int' ?

When I replaced '%d' with '%ld' the warning went.


回答1:


The sizeof operator is processed at compile time (and can be applied on both types and expressions). It gives some constant* of type size_t. On your system (and mine Debian/Linux/x86-64 also) sizeof(int) is (size_t)4. That size_t type is often typedef-ed in some type like unsigned long (but what integral type it actually is depends upon the implementation). You could code

printf("%d", (int)sizeof(int));

or (since printf understands the %zd or %zu control format string for size_t)

printf("%zu", sizeof(int));

For maximum portability, use %zu (not %ld) for printing size_t (because you might find systems or configurations on which size_t is unsigned int etc...).

Note *: sizeof is always constant, except for VLA



来源:https://stackoverflow.com/questions/40798554/how-sizeof-operator-works-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!