sizeof

From RAD Studio
Jump to: navigation, search

Go Up to Keywords, Alphabetical Listing Index


Category

Operators (C++)

Description

The sizeof operator has two distinct uses:

sizeof unary-expression
sizeof (type-name)

The result in both cases is an integer constant that gives the size in bytes of how much memory space is used by the operand (determined by its type, with some exceptions). The amount of space that is reserved for each type depends on the machine.

In the first use, the type of the operand expression is determined without evaluating the expression (and therefore without side effects). When the operand is of type char (signed or unsigned), sizeof gives the result 1. When the operand is a non-parameter of array type, the result is the total number of bytes in the array (in other words, an array name is not converted to a pointer type). The number of elements in an array equals sizeof array / sizeof array[0].

If the operand is a parameter declared as array type or function type, sizeof gives the size of the pointer. When applied to structures and unions, sizeof gives the total number of bytes, including any padding.

You cannot use sizeof with expressions of function type, incomplete types, parenthesized names of such types, or with an lvalue that designates a bit field object.

The integer type of the result of sizeof is size_t.

You can use sizeof in preprocessor directives; this is specific to C++Builder.

In C++, sizeof(classtype), where classtype is derived from some base class, returns the size of the object (remember, this includes the size of the base class).

Example

/*  USE THE sizeof OPERATOR TO GET SIZES OF DIFFERENT DATA TYPES. */
#include <stdio.h>
struct st {
   char *name;
   int age;
   double height;
 };
struct st St_Array[]= {  /* AN ARRAY OF structs */
   { "Jr.",     4,  34.20 },  /* St_Array[0] */
   { "Suzie",  23,  69.75 },  /* St_Array[1] */
 };
int main()
   {
     long double LD_Array[] = { 1.3, 501.09, 0.0007, 90.1, 17.08 };
     printf("\nNumber of elements in LD_Array = %d",
     sizeof(LD_Array) / sizeof(LD_Array[0]));
     /****  THE NUMBER OF ELEMENTS IN THE St_Array. ****/
      printf("\nSt_Array has %d elements",
      sizeof(St_Array)/sizeof(St_Array[0]));
      /****  THE NUMBER OF BYTES IN EACH St_Array ELEMENT.  ****/
      printf("\nSt_Array[0] = %d", sizeof(St_Array[0]));
      /****  THE TOTAL NUMBER OF BYTES IN St_Array.  ****/
      printf("\nSt_Array=%d", sizeof(St_Array));
      return 0;
   }

Output

Number of elements in LD_Array = 5
St_Array has 2 elements
St_Array[0] = 16
St_Array= 32