HPlogo HP C/HP-UX Reference Manual: Version A.05.55.02 > Chapter 5 Expressions and Operators

sizeof Operator

» 

Technical documentation

Complete book in PDF

 » Table of Contents

 » Index

Syntax

sizeof exp;

sizeof (type_name)

Arguments

exp

An expression of any type except function, void, or bit field.

type_name

The name of a predefined or user-defined data type, or the name of some variable. An example of a predefined data type is int. A user-defined data type could be the tag name of a structure.

Description

The sizeof unary operator finds the size of an object. It accepts two types of operands: an expression or a data type. If the type of the operand is a variable length array, the operand is evaluated - the compiler only determines what type the result would be for the expression operand. Any side effects in the expression, therefore, will not have an effect. The result type of the sizeof operator is size_t.

If the operand is an expression, sizeof returns the number of bytes that the result occupies in memory:

/* Returns the size of an int (4 if ints are four bytes long) */
sizeof(3 + 5)

/* Returns the size of a double (8 if doubles are
* eight bytes long)
*/
sizeof(3.0 + 5)

/* Returns the size of a float (4 if floats are
* four bytes long)
*/
float x;
sizeof(x)

For expressions, the parentheses are optional, so the following is legal:

sizeof x

By convention, however, the parentheses are usually included.

The operand can also be a data type, in which case the result is the length in bytes of objects of that type:

sizeof(char) /* 1 on all machines */
sizeof(short) /* 2 on HP 9000 Series */
sizeof(float) /* 4 on HP 9000 Series */
sizeof(int *) /* 4 on HP 9000 Series */

The parentheses are required if the operand is a data type.

NOTE: The results of most sizeof expressions are implementation dependent. The only result that is guaranteed is the size of a char, which is always 1.

In general, the sizeof operator is used to find the size of aggregate data objects such as arrays and structures.

Example

You can use the sizeof operator to obtain information about the sizes of objects in your C environment. The following prints the sizes of the basic data types:

/* Program name is "sizeof_example". This program
* demonstrates a few uses of the sizeof operator.
*/
#include <stdio.h>
int main(void)
{
printf("TYPE\t\tSIZE\n\n");
printf("char\t\t%d\n", sizeof(char));
printf("short\t\t%d\n", sizeof(short));
printf("int\t\t%d\n", sizeof(int));
printf("float\t\t%d\n", sizeof(float));
printf("double\t\t%d\n", sizeof(double));
}

If you execute this program, you get the following output:

TYPE SIZE

char 1
short 2
int 4
float 4
double 8

© Hewlett-Packard Development Company, L.P.