C - Operator sizeof Operator

Introduction

You can find out how many bytes are occupied by a given type by using the sizeof operator.

sizeof(int) returns the number of bytes occupied by a variable of type int, and the result is an integer of type size_t.

size_t is defined in the standard header file stddef.h, as well as several other headers.

size_t size = sizeof(long long);

You can apply the sizeof operator to an expression.

In that case the result is the size of the value that results from evaluating the expression.

The following code will output the number of bytes occupied by each numeric type:

Demo

#include <stdio.h>

int main(void)
{
      printf("Variables of type char occupy %u bytes\n", sizeof(char));
      printf("Variables of type short occupy %u bytes\n", sizeof(short));
      printf("Variables of type int occupy %u bytes\n", sizeof(int));
      printf("Variables of type long occupy %u bytes\n", sizeof(long));
      printf("Variables of type long long occupy %u bytes\n", sizeof(long long));
      printf("Variables of type float occupy %u bytes\n", sizeof(float));
      printf("Variables of type double occupy %u bytes\n", sizeof(double));
      printf("Variables of type long double occupy %u bytes\n", sizeof(long double));
      return 0;//from   w w  w  .  jav a2 s.c  o m
}

Result

sizeof operator results in an unsigned integer value, so output it using the %u specifier.

You can get the number of bytes occupied by a variable, var_name, with the expression sizeof var_name.

To use the sizeof operator to a type, the type name must be between parentheses, like this: sizeof(long double).

To use sizeof to an expression, the parentheses are optional.

Related Topics

Quiz