Ok so... size_t is exactly the same thing as unsigned int? There is nothing that great about it then?
No. size_t is an unsigned integral type, but it need not be unsigned int. It's entirely possible for size_t and unsigned int to be different sizes; 64- and 32-bit respectively, for example.
And what about a function that accepts a size_t variable? Would that mean that it accepts any type of variable (the value returned by sizeof) or does it mean that it only accepts unsigned ints?
That's a mildly complex question, because C can do all sorts of conversions between types, and the sizes of types are not mandated by the C standard. If a function takes a size_t argument, anything you pass will be converted to size_t, however that happens.
If you pass an integral value that happens to fit inside a size_t (that is, it's not negative and it's less than size_t's largest value {SIZE_MAX on C99}), then it will retain its value.
If you pass an integral value that is outside of the range of what size_t can hold, it will be modified to fit, using these rules as quoted from C99: "[T]he value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type."
If you pass a floating point value, the first thing that happens is that the fractional part is discarded. If the resulting (integral) value doesn't fit inside of a size_t, the behavior of your program is undefined (which you might guess is a bad thing). If the value does fit, then it's stored as-is.
This program sort of demonstrates what's going on. It assumes that SIZE_MAX + 1.0 is a valid double value, which is a pretty reasonable assumption. This requires a C99 implementation:
Code:
#include <stdio.h>
#include <stdint.h>
static void f(size_t s)
{
printf("%zu\n", s);
}
int main(void)
{
f(1); /* int; Fits into size_t. */
f(-1); /* int; Doesn't fit; defined behavior. */
f(1.1); /* double; Fits when .1 is discarded. */
f(SIZE_MAX + 1.0); /* double; Doesn't fit after discarding, undefined behavior. */
return 0;
}
I ran this with three compilers: gcc, Intel's C compiler, and Sun Studio 12. They all agreed on the first three outputs: 1, 4294967295, 1. All compilers will output the values 1, SIZE_MAX, and 1 for these (pretending for a moment that I don't have that undefined behavior in the last one; because of it, anything goes). However, the compilers differ on the last value. Intel and Sun output 0; gcc outputs 4294967295. Both of these are "correct" because the behavior is undefined; they can print (or do!) anything they please.