• Home
  • 1.13 sizeof Operator

1.13 sizeof Operator

View Categories

1.13 sizeof Operator

1 min read

Table of Contents

The sizeof operator determines the size of a data type or object in bytes. It is commonly used to calculate memory requirements and to write programs that work across different platforms.

This example demonstrates how to determine the size of fundamental data types.

Source Code #

#include <iostream>

int main()
{
    std::cout << "Size of char: " << sizeof(char) << " byte(s)\n";
    std::cout << "Size of int: " << sizeof(int) << " byte(s)\n";
    std::cout << "Size of float: " << sizeof(float) << " byte(s)\n";
    std::cout << "Size of double: " << sizeof(double) << " byte(s)\n";

    return 0;
}

Output #

Size of char: 1 byte(s)
Size of int: 4 byte(s)
Size of float: 4 byte(s)
Size of double: 8 byte(s)

The reported sizes are implementation-dependent and may vary depending on the compiler, target architecture, and platform.

Explanation #

  • sizeof is a compile-time operator that returns the size of a type or object in bytes.
  • sizeof(char) always returns 1 because a byte is defined as the size of a char in C++.
  • sizeof(int) returns the number of bytes occupied by the int data type on the target platform.
  • sizeof(float) returns the storage size of a single-precision floating-point value.
  • sizeof(double) returns the storage size of a double-precision floating-point value.
  • The result of sizeof has the type std::size_t, an unsigned integer type capable of representing object sizes.
  • The exact size of most fundamental data types is implementation-defined. Only their minimum size requirements are specified by the C++ standard.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *