Search code examples
ctype-conversionsizeofunsigned-integersize-t

Can I store the yield value of sizeof of type size_t in an unsigned int object?


sizeof is a standard C operator.

sizeof yields the size (in bytes) of its operand in type size_t, Quote from ISO/IEC 9899:2018 (C18), 6.5.3.4/5. Phrases surrounded by -- are my addition for clarification of context:

The value of the result of both operators -- (sizeof and _Alignof) -- is implementation-defined, and its type (an unsigned integer type) is size_t, defined in <stddef.h> (and other headers).

Implicitly, if I want my program to be standard conform and want to use sizeof, I need to include one of the header files in which size_t is defined, because the value it yields is of type size_t and I want to store the value in an appropriate object.

Of course, in any program which would not be a toy program I would need at least one of these headers all the way up regardless but in a simple program I need to explictly include those headers, although I do not need them otherwise.

Can I use an unsigned int object to store the size_t value sizeof yields without an explicit cast?

Like for example:

char a[19];
unsigned int b = sizeof(a);

I compiled that with gcc and -Wall and -Werror option flag but it did not had anything to complain.

But is that standard-conform?


Solution

  • It is permissible but it is your responsibility to provide that there will not be an overflow storing a value of the type size_t in an object of the type unsigned int. For unsigned integer types overflow is well-defined behavior.

    However it is a bad programming style to use types that were not designed to store values of a wider integer type. This can be a reason of hidden bugs.

    Usually the type size_t is an alias for the type unsigned long. On some 64-bit systems, the type unsigned long has the same size as the type unsigned long long, which is 8 bytes instead of the 4 bytes that unsigned int can be stored in.