The operator sizeof

Location
  1. Courses

    /

  2. Complete C++ Course

    /

  3. The basics

    /

  4. The operator sizeof

Retrieving the size of variable types

We saw earlier that the size (In bytes) of primitives is not fixed (Except for char and unsigned char) and is varying depending on the compiler used. It is however possible to retrieve the number of bytes a type takes in memory using the operator sizeof. It is done by simply adding the name of the type, between parentheses, after the keyword sizeof.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream> struct MyStruct{ int a; int b; }; int main() { std::cout << sizeof(int) << std::endl; // Prints the size of the type int. Example, 4. std::cout << sizeof(long long) << std::endl; // Prints the size of the type long long. Example, 8. std::cout << sizeof(float) << std::endl; // Prints the size of the type float. Example, 4. std::cout << sizeof(double) << std::endl; // Prints the size of the type double. Example, 8. // Prints the size of the type struct MyStruct. Example, 8. std::cout << sizeof(struct MyStruct) << std::endl; return 0; }

Retrieving the size of static arrays

The operator sizeof can also by used to retrieve the size, in bytes, of a static array. Note that it only works with static arrays and not pointers that point to an array. Giving a pointer to the operator sizeof will return the size of the pointer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream> int main() { int array[6]; int* ptr = &array; std::cout << sizeof(array) << std::endl; // Prints the size in memory of the array. Example, 24. std::cout << sizeof(int*) << std::endl; // Prints the size of a pointer. Example, 8. std::cout << sizeof(ptr) << std::endl; // Prints the size of a pointer. Example, 8. return 0; }