Menu Close

C Programming: The sizeof Operator

sizeof() is a unary operator in the C language, like other operators such as ++ and –, it is not a function.

The sizeof operator in C programming is a unary operator that is used to determine the size in bytes of a data type, expression, or variable. It allows you to calculate the memory occupied by a particular data type or variable at compile time.

The syntax of the sizeof operator is as follows:

sizeof (operand)

The sizeof() operator provides the storage size of its operand in bytes. The operand can be an expression or a type name enclosed in parentheses.

The storage size of the operand is determined by the type of the operand.

Here, the operand can be one of the following:

  1. Data type: You can use sizeof with a data type to get the size of that data type. For example, sizeof(int) will give you the size of an integer in bytes.
  2. Variable: You can use sizeof with a variable to get the size of that variable. For example, sizeof(x) will give you the size of variable x.
  3. Expression: You can use sizeof with an expression to get the size of the resulting type after evaluating the expression. For example, sizeof(a + b) will give you the size of the result of the addition of variables a and b.

The sizeof operator returns the size of its operand in terms of the number of bytes. The size of a data type is determined by the compiler and the platform on which the code is compiled. The size can vary depending on the compiler, the target architecture, and the operating system.

It is important to note that sizeof is not a function, but an operator built into the C language. It is evaluated at compile time, and the result is a constant value that can be used in various programming constructs.

The result of sizeof of different data types (which may vary on different platforms) :

sizeof(char) = 1;
sizeof(unsigned char) = 1;
sizeof(signed char) = 1;
sizeof(int) = 4;
sizeof(unsigned int) = 4;
sizeof(short int) = 2;
sizeof(unsigned short) = 2;
sizeof(long int) = 4;
sizeof(unsigned long) = 4;
sizeof(float) = 4;
sizeof(double) = 8;
sizeof(long double) = 12;

example 1: The sizeof() Operator

#include <stdio.h>
int main()
{
    int a;
    float b;
    double c;
    char d;
    printf("Size of int=%lu bytes\n",sizeof(a));
    printf("Size of float=%lu bytes\n",sizeof(b));
    printf("Size of double=%lu bytes\n",sizeof(c));
    printf("Size of char=%lu byte\n",sizeof(d));

    return 0;
}

Results:

Size of int = 4 bytes
Size of float = 4 bytes
Size of double = 8 bytes
Size of char = 1 byte

 

Related Posts

Leave a Reply