Code Skiller logoCB Logo
Logo LearnLearnLogo PracticePracticeLogo HireHireLogo IDEIDE

Size of ( ) Operator

User image

Published by

sanya sanya

Published at: 26th Jul, 2023
1.465 mins read

The ‘sizeof()’ operator is a compile-time unary operator in C++ that allows you to determine the size in bytes of a data type or a variable. It returns the size of the operand in terms of the number of bytes.

When to use:

You can use the ‘sizeof()’ operator when you need to determine the size of a data type or a variable at compile time. It is particularly useful when working with arrays, dynamically allocating memory, or when you want to ensure that you are correctly allocating memory for a particular data type.

Syntax:

sizeof(type)

sizeof(expression)

Code example:

#include

using namespace std;

int main() {

int num = 5;

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

cout << "Size of num: " << sizeof(num) << " bytes" << endl;

double arr[5];

cout << "Size of arr: " << sizeof(arr) << " bytes" << endl;

return 0;

}

Output:

Size of int: 4 bytes

Size of num: 4 bytes

Size of arr: 40 bytes

In this example, ‘sizeof(int)’ returns the size of the ‘int’ data type, which is typically 4 bytes on most systems. ‘sizeof(num)’ returns the size of the variable ‘num’, which is also 4 bytes since it is an ‘int’.

The ‘sizeof(arr)’ returns the size of the array ‘arr’, which is calculated by multiplying the size of each element (‘sizeof(double)’) by the number of elements in the array (5). The output shows that the size of the ‘arr’ array is 40 bytes.

Note: The actual size of a data type may vary depending on the system and compiler being used. The ‘sizeof()’ operator provides the size in terms of bytes, and it is evaluated at compile time.

Library

WEB DEVELOPMENT

FAANG QUESTIONS