sizeof

Is sizeof() in Bytes?

Yes, sizeof() returns sizes in bytes in C and C++. Learn what a byte means here, how sizeof works with arrays, and why it counts bytes, not elements.

On this page
  1. Short answer
  2. What a byte means in C and C++
  3. Examples with basic types
  4. Bytes, not elements
  5. The result type: size_t
  6. In short

Short answer

Yes. sizeof gives the size of a type or an object in bytes. If sizeof(int) returns 4, then an int takes four bytes on that system. The result is a count of bytes, not a count of items.

What a byte means in C and C++

In C and C++, a byte is the size of a char. The standard requires a char to be at least 8 bits wide, and on nearly all current systems it is exactly 8. So in practice a byte is 8 bits.

This also settles a common question. Is char always 1 byte in C? Yes. The standard defines sizeof applied to a char as 1, so sizeof(char) is always 1.

Examples with basic types

#include <iostream>

int main() {
    char letter = 'A';
    int count = 0;
    double ratio = 0.0;
    std::cout << sizeof(letter) << "\n";  // 1
    std::cout << sizeof(count) << "\n";   // often 4
    std::cout << sizeof(ratio) << "\n";   // often 8
}

The int and double values depend on the platform, which is why the comments say “often.” The char value is always 1.

Bytes, not elements

For an array, sizeof reports the total number of bytes in the array, not the number of elements:

int numbers[5] = {1, 2, 3, 4, 5};
std::cout << sizeof(numbers) << "\n";                       // 20 when int is 4 bytes
std::cout << sizeof(numbers) / sizeof(numbers[0]) << "\n";  // 5 elements

To get the element count, divide the total by the size of one element. This works only when the name refers to the array itself. If the array has been passed to a function, it has decayed to a pointer, and sizeof reports the pointer’s size instead.

The result type: size_t

sizeof returns a size_t, which is an unsigned integer type. Mixing it with a signed int in a comparison can give a surprise:

int offset = -1;
if (offset < sizeof(int)) {
    // false: -1 becomes a very large size_t
}

The negative value is converted to an unsigned type before the comparison, so the test is false. If you need to store a sizeof result in an int, and you know the value is small, cast it explicitly, as in static_cast<int>(sizeof(value)).

In short

sizeof returns sizes in bytes. A byte is the size of a char, which is always 1. For arrays, the result is the total bytes, so divide by the size of one element to count the elements.

The complete guide to sizeof

The sizeof Operator in C++
Read the guide

Keep exploring

Guides from other topics

All topics →

Unary Operators in C++

Learn what unary operators in C++ are, from the one-operand symbols like !, ~, ++ and * to prefix vs postfix, precedence and common mistakes, with examples.