C Programming Tutorial

C Programming Tutorial

Sizeof Operators in C

Hello Everyone, In this article, we will cover the concept of Sizeof Operators in C. This operator helps you optimize memory usage and ensure efficient coding practices. Whether you’re new to C or have some experience, this guide will help you to understand concet of Sizeof Operators in C effectively. Let’s get started.

The sizeof operator in C programming is a compile-time operator used to determine the size (in bytes) of a data type, variable, or an object. It returns the number of bytes required to store the object or the data type in memory. The sizeof operator is particularly useful in memory allocation, array manipulation, and other operations that require knowledge of the size of data types or objects.

Syntax for the sizeof operator

sizeof(data_type)

or

sizeof(variable)

Now let’s take a look at some more examples of using the sizeof operator in C:

1. Using sizeof with basic data types:

    #include <stdio.h>
    int main() {
        printf("Size of char: %zu bytes\\n", sizeof(char));
        printf("Size of int: %zu bytes\\n", sizeof(int));
        printf("Size of float: %zu bytes\\n", sizeof(float));
        printf("Size of double: %zu bytes\\n", sizeof(double));
        printf("Size of long int: %zu bytes\\n", sizeof(long int));
        printf("Size of long long int: %zu bytes\\n", sizeof(long long int));
    
        return 0;
    }
    

    The output of this program will show the size of each data type in bytes, which may vary depending on the architecture and compiler used.

    2. Using sizeof with variables:

      #include <stdio.h>
      int main() {
          int a;
          float b;
          double c;
      
          printf("Size of int a: %zu bytes\\n", sizeof(a));
          printf("Size of float b: %zu bytes\\n", sizeof(b));
          printf("Size of double c: %zu bytes\\n", sizeof(c));
      
          return 0;
      }

      In this example, the sizeof operator returns the size of the variables a, b, and c.

      3. Using sizeof with arrays:

        #include <stdio.h>
        int main() {
            int arr[] = {1, 2, 3, 4, 5};
            int arr_size = sizeof(arr) / sizeof(arr[0]);
            printf("Size of array: %zu bytes\\n", sizeof(arr));
            printf("Number of elements in array: %d\\n", arr_size);
        
            return 0;
        }

        In this example, the sizeof operator calculates the total size of the array in bytes and the number of elements in the array by dividing the total size by the size of an individual element.

        Keep in mind that the sizeof operator returns a value of type size_t, which is an unsigned integer type. When using printf, use the %zu format specifier to correctly display the value.

        Share This Article