The sizeof operator

sizeof will return the number of bytes reserved for a variable or data type.

The following code shows sizeof returning the length of a data type.

        /* How big is an int? expect an answer of 4. */
	   printf("%d \n", sizeof(int));

sizeof will also return the number of bytes reserved for a structure.

        /* Will print 8 on most machines. */
	    int a;
	    int b;
	  } TwoInts;
	printf("%d \n", sizeof(TwoInts));

Finally, sizeof will return the length of a variable.

	  char String[20];
	  printf ("%d \n", sizeof String);
 	  printf ("%d \n", sizeof (String));

In the example above I have printed the size of 'String' twice. This is to show that when dealing with variables, the brackets are optional. I recommend that you always place the brackets around the sizeof argument.

sizeof can be used to find the maximum value which can be stored in a valid integer datatype through these macros:

#define umaxvalue(t) (((0x1ULL << ((sizeof(t) * 8ULL) - 1ULL)) - 1ULL) | \
                    (0xFULL << ((sizeof(t) * 8ULL) - 4ULL)))

#define smaxvalue(t) (((0x1ULL << ((sizeof(t) * 8ULL) - 1ULL)) - 1ULL) | \
                    (0x7ULL << ((sizeof(t) * 8ULL) - 4ULL)))

#define issigned(t) (((t)(-1)) < ((t) 0))

#define maxvalue(t) ((unsigned long long) (issigned(t) ? smaxvalue(t) : umaxvalue(t)))

For example

int main(int argc, char** argv) {
    printf("schar: %llx uchar: %llx\n", maxvalue(char), maxvalue(unsigned char));
    printf("sshort: %llx ushort: %llx\n", maxvalue(short), maxvalue(unsigned short));
    printf("sint: %llx uint: %llx\n", maxvalue(int), maxvalue(unsigned int));
    printf("slong: %llx ulong: %llx\n", maxvalue(long), maxvalue(unsigned long));
    printf("slong long: %llx ulong long: %llx\n", maxvalue(long long), maxvalue(unsigned long long));
    return 0;

If you'd like, you can toss a '(t)' onto the front of those macros so they give you a result of the type that you're asking about, and you don't have to do casting to avoid warnings.


Example 1 Data types.

Example 2 Data objects.

See also:

The strlen function.

Other operators

malloc function.

Top Master Index Keywords Functions

Martin Leslie