Sizeof Operator In C++ - C++ Programming Tutorial
C++ Course / Miscellaneous / Sizeof Operator In C++

Sizeof Operator In C++

BLUF: Mastering Sizeof Operator In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Sizeof Operator In C++

C++ is renowned for its efficiency. Learn how Sizeof Operator In C++ enables low-level control and high-performance computing in the tutorial below.

In C++, the sizeof operator is utilized to determine the size of data types, constants, and variables. This operator is evaluated at compile time and provides the size of variables or constants during compilation. This feature is particularly beneficial in system-level programming, memory allocation, and ensuring portability.

The size represents the memory consumed in a computer system, determined using the sizeof operator.

Syntax

It has the following syntax:

Example

sizeof(data_type);

In the provided syntax, the data_type signifies the type of data associated with variables, constants, unions, structures, or any other custom-defined data type.

Usage of sizeof Operator in Operands

The sizeof operator can be used with the following types of operands:

When an operand is of data type

If the argument of a sizeof function includes the data type of a variable, the sizeof function will provide the size of that data type. Let's illustrate this situation with an instance.

Example

Example

#include <iostream>  

using namespace std;   //using standard namespace

int main()   //main function

{  

  // Determining the space in bytes occupied by each data type.  

  cout << "Size of integer data type : " <<sizeof(int)<< endl;  

  cout << "Size of float data type : " <<sizeof(float)<< endl;  

  cout << "Size of double data type : " <<sizeof(double)<< endl;  

  cout << "Size of char data type : " <<sizeof(char)<< endl;  

  return 0;  

}

Output:

Output

Size of integer data type : 4

Size of float data type : 4

Size of double data type : 8

Size of char data type : 1

Explanation:

In this instance, we examined the dimensions of the predefined data types by employing the sizeof function. It is common knowledge that an integer requires 4 bytes, a floating-point number needs 4 bytes, a double precision floating-point number necessitates 8 bytes, and a character takes up 1 byte. The sizeof function confirmed these sizes.

When an operand is of Class type

In C++, when the operand of the sizeof operator is a class type, it yields the overall size (in bytes) of an instance of that class. To illustrate this concept, let's delve into an example.

Example

Example

#include <iostream>  

using namespace std;    //using standard namespace

class Base  

{  

int a;  

};  

int main()    //main function

{  

Base b;  

std::cout << "Size of class base is : "<<sizeof(b) << std::endl;  

return 0;  

}

Output:

Output

Size of class base is : 4

Explanation:

In this instance, we assessed the dimensions of the class containing a solitary integer variable. Subsequently, the result will be 4 bytes since the integer variable takes up 4 bytes of memory.

If a char variable and multiple integer values are included in a class, the code snippet will appear as follows:

Example

Example

#include <iostream>  

using n#include <iostream>  

using namespace std;    //using standard namespace

class Base  

{  

    int a;  

    int d;  

    char ch;  

};  

int main()    //main function

{  

  Base b;  

  cout << "Size of class base is : "<<sizeof(b) << endl;  

    return 0;  

}

amespace std;    //using standard namespace

class Base  

{  

int a;  

};  

int main()    //main function

{  

Base b;  

std::cout << "Size of class base is : "<<sizeof(b) << std::endl;  

return 0;  

}

Output:

Output

Size of class base is : 12

Explanation:

In this instance, the class contains a pair of integer variables and a single char variable. Initially, one might expect the class size to be 9 bytes (int + int + char). However, this assumption is inaccurate as it overlooks the impact of structure padding.

When an operand is of array type

In C++, when the sizeof operator is applied to an array, it computes the total size in bytes occupied by the complete array, rather than just the array's pointer. Let's illustrate this concept through a demonstration.

Example

Example

#include <iostream>  

using namespace std;   //using standard namespace

 int main()   //main function

{  

  int arr[]={10,20,30,40,50};  

  cout << "Size of the array 'arr' is : "<<sizeof(arr) << endl;  

  return 0;  

}

Output:

Output

Size of the array 'arr' is : 20

Explanation:

In this instance, we've defined an integer array comprising five elements. The array's size was determined through the application of the sizeof function. Based on the computation, the array's size is anticipated to be 20 bytes because each integer data type consumes 4 bytes, and the array consists of 5 elements, resulting in a total memory allocation of 5 * 4 = 20 bytes.

When an operand is of pointer type

When working with C++, when the sizeof operator is applied to a pointer type's operand, it will provide the size of the pointer, not the object it points to. To illustrate this concept, let's explore a practical example.

Example

Example

#include <iostream>  

using namespace std;    //using standard namespace

int main()    //main function

{  

    int *ptr1=new int(10);  

    cout << "size of ptr1 : " <<sizeof(ptr1)<< endl;                                                                                                                                                                                                                                  

   cout << "size of *ptr1 : " <<sizeof(*ptr1)<< endl;  

   char *ptr2=new char('a');  

   cout <<"size of ptr2 : " <<sizeof(ptr2)<< endl;  

   cout <<"size of *ptr2 : "<<sizeof(*ptr2)<< endl;  

   double *ptr3=new double(12.78);  

    cout <<"size of ptr3 : " <<sizeof(ptr3)<< endl;  

   cout <<"size of *ptr3 : "<<sizeof(*ptr3)<< endl;  

    return 0;  

}

Output:

Output

size of ptr1 : 8

size of *ptr1 : 4

size of ptr2 : 8

size of *ptr2 : 1

size of ptr3 : 8

size of *ptr3 : 8

Explanation:

In this instance, we have identified the dimensions of pointers. Pointer size is consistent across all data types. On a 32-bit OS, pointers are 4 bytes in size, while on a 64-bit OS, they are 8 bytes in size.

When an operand is an expression

In C++, when the operand of the sizeof operator is an expression, the expression itself is not actually executed. Instead, it is simply used to identify the type of the expression. The sizeof operator then calculates the size at compile time. This concept can be clarified through an illustrative example.

Example

Example

#include <iostream>  

using namespace std;     //using standard namespace

int main()    //main function

{  

   int num1;  

   double num2;  

   cout << sizeof(num1+num2);  

     return 0;  

}

Output:

Explanation:

In this instance, we've defined a pair of variables, num1 and num2, with int and double data types. An int typically uses 4 bytes of memory, whereas a double occupies 8 bytes. Subsequently, the outcome will be stored in a double variable, requiring 8 bytes of memory space.

Size of union

In C++, a union is a distinct data type where all members share the identical memory location. This implies that only a single member can occupy the union at a given time. The union's size is determined by the largest member it contains, as the memory space must be sufficient to hold this largest member.

This characteristic is advantageous in scenarios with limited memory capacity, like embedded systems or hardware development, where it is essential to store various data types in a single memory location.

C++ Size of Union Example

Let's consider an example to demonstrate the magnitude of the union in C++.

Example

Example

#include <iostream>

using namespace std;  //using standard namespace

union Data {

    int i;

    float f;

    double d;

    char c;

};

int main() {   //main function

    Data data;

    cout << "Size of union Data: " << sizeof(data) << " bytes" << endl;

    cout << "Size of int: " << sizeof(data.i) << " bytes" << endl;

    cout << "Size of float: " << sizeof(data.f) << " bytes" << endl;

    cout << "Size of double: " << sizeof(data.d) << " bytes" << endl;

    cout << "Size of char: " << sizeof(data.c) << " bytes" << endl;

    return 0;

}

Output:

Output

Size of union Data: 8 bytes

Size of int: 4 bytes

Size of float: 4 bytes

Size of double: 8 bytes

Size of char: 1 bytes

Explanation:

In this instance, we've consolidated data from int, float, double, and char types into a union. Within the main function, the sizeof operator is utilized to reveal the size of both the entire union and each individual member. Due to a union utilizing common memory, its overall size matches that of the largest member, which is double in this scenario.

Size of Constants

In C++, constants are fixed values that remain unchanged throughout the execution of a program. These constants can take on various forms like int, float, double, char, and so on. The size of a constant depends on its data type, much like how it works for variables. The sizeof operator is applicable to constants directly, aiding in the evaluation of their sizes. This operator proves useful when analyzing memory consumption or managing type conversions in computations.

C++ Size of Constant Example

Let's consider an example to demonstrate the magnitude of constants in C++.

Example

Example

#include <iostream>

using namespace std;   //using standard namespace

int main() {   //main function

    cout << "Size of integer constant 10: " << sizeof(25) << " bytes" << endl;

    cout << "Size of float constant 10.5f: " << sizeof(9.5f) << " bytes" << endl;

    cout << "Size of double constant 10.5: " << sizeof(10.5) << " bytes" << endl;

    cout << "Size of char constant 'T': " << sizeof('T') << " bytes" << endl;

    cout << "Size of string constant \"Hello\": " << sizeof("Hello") << " bytes" << endl;

    return 0;

}

Output:

Output

Size of integer constant 10: 4 bytes

Size of float constant 10.5f: 4 bytes

Size of double constant 10.5: 8 bytes

Size of char constant 'T': 1 bytes

Size of string constant "Hello": 6 bytes

Explanation:

In this instance, we are utilizing the sizeof operator to showcase the sizes of different constants: an integer (25), a floating-point number (9.5f), a double-precision floating-point number (10.5), a character ('T'), and a string literal (Hello).

Nested sizeof Operator

In C++, the concept of the nested sizeof function involves utilizing the sizeof operator within another sizeof operator. The sizeof operator, which yields a size_t type (an unsigned integer type), enables us to ascertain the memory space required to store the size value on the particular system.

C++ Nested Sizeof Operator Example

Let's consider a scenario to demonstrate the Nested Sizeof operator in C++.

Example

Example

#include <iostream>

using namespace std;   //using standard namespace

int main() {   //main function

    int a = 5;

    double b = 12.5;

    cout << "Size of sizeof(a + b): " << sizeof(sizeof(a + b)) << " bytes" << endl;

    cout << "Size of (sizeof(char) * 5): " << sizeof(sizeof(char) * 5) << " bytes" << endl;

    return 0;

}

Output:

Output

Size of sizeof(a + b): 8 bytes

Size of (sizeof(char) * 5): 8 bytes

Explanation:

In this instance, we illustrate the application of a nested sizeof operator. In the initial line, the size of the outcome of sizeof(a + b) is evaluated; wherein a + b is a double, and sizeof(.) represents an integer type. Subsequently, the following line computes the size of sizeof(char) * 5, resulting in an integer expression.

sizeof operator in C++ FAQs

1) Why is the sizeof operator used in C++?

It serves the purpose of determining the byte size of a data type, variable, array, or expression during compilation.

2) Does sizeof analyze expressions within it?

No, the sizeof operator is determined during compilation and does not examine the expression's value, but rather its data type.

3) What type of value does sizeof give?

It provides a result of type size_t, which represents an unsigned integral data type.

4) What is the output of sizeof("Hello")?

The result is 6 since string constants are terminated with a null character (\0) at the end.

5) Is sizeof executed at runtime or compile time?

It runs during compilation, unless employed with a variable-sized array.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience