×

C++ Tutorial

C++ Data types

C++ Operators & Keywords

C++ Conditional Statements

C++ Functions

C++ 'this' Pointer, References

C++ Class & Objects

C++ Constructors & Destructors

C++ Operator overloading

C++ 11 (Advance C++)

C++ Preparation

C++ Header Files & Functionsr

Data Structure with C++

C++ - Miscellaneous

C++ Programs

sizeof() Operator in C/C++

C/C++ sizeof() Operator: In this tutorial, we are going to discuss the details about the sizeof() operator in C/C++ starting from its usage, examples to applications.
Submitted by Radib Kar, on July 07, 2020

Definition of sizeof() operator

sizeof operator is a unary operator that takes a single operand and the operand can be data type, variables, objects, expressions, and anything that has a size, i.e., that acquires some memory. We will see in the example section usage of sizeof operator which you may have never even though of.

Details of sizeof() operator

Operator type Unary
Operands data types, expressions, variables, objects
Overloading It can't be overloaded
Precedence Same as other unary operators, after the postfix operators
Associativity Right to left
Usage Size of the return amount of memory allocated in bytes

sizeof() operator on datatypes

As we know different versions of compilers assign the different amounts of memory to data types. Like, in earlier versions, integers were assigned memory of 2 bytes, whereas in the latest versions it’s 4 bytes. We can easily check that by using the sizeof operator.

Example

#include <stdio.h>

int main()
{
    printf("size of integer data type is: %lu\n", sizeof(int));
    printf("size of float data type is: %lu\n", sizeof(float));
    printf("size of double data type is: %lu\n", sizeof(double));
    printf("size of character data type is: %lu\n", sizeof(char));

    return 0;
}

Output:

size of integer data type is: 4
size of float data type is: 4
size of double data type is: 8
size of character data type is: 1

sizeof operator on variables, expressions

We can also use the sizeof operator to find the size of any variable, expressions. The below program shows how to use the sizeof operator to find the size of any variable.

Example

#include <stdio.h>

int main()
{
    int a;
    char b;
    float c;
    double d;
    long e;
    long long f;
    long long int g;

    printf("sizeof a which is of type int is: %lu\n", sizeof(a));
    printf("sizeof a which is of type char is: %lu\n", sizeof(b));
    printf("sizeof a which is of type float is: %lu\n", sizeof(c));
    printf("sizeof a which is of type double is: %lu\n", sizeof(d));
    printf("sizeof a which is of type long is: %lu\n", sizeof(e));
    printf("sizeof a which is of type long long is: %lu\n", sizeof(f));
    printf("sizeof a which is of type long long int is: %lu\n", sizeof(g));

    return 0;
}

Output:

sizeof a which is of type int is: 4
sizeof a which is of type char is: 1
sizeof a which is of type float is: 4
sizeof a which is of type double is: 8
sizeof a which is of type long is: 8
sizeof a which is of type long long is: 8
sizeof a which is of type long long int is: 8

Example

The below program shows how to use sizeof operator to find the size of any expression,

#include <stdio.h>

int main()
{
    int a = 9;
    char b = 'a';
    float c = 8.7;
    double d = 0.99;
    long e = 12;
    long long f = 13;
    long long int g = 16;

    printf("sizeof a+c which is of type int+float is: %lu\n", sizeof(a + c));
    printf("sizeof c+d which is of type float+doyble is: %lu\n", sizeof(c + d));
    printf("sizeof a+e which is of type int+long is: %lu\n", sizeof(a + e));
    printf("sizeof a+c+f which is of type int+float+long long is: %lu\n", sizeof(a + c + f));

    return 0;
}

Output:

sizeof a+c which is of type int+float is: 4
sizeof c+d which is of type float+doyble is: 8
sizeof a+e which is of type int+long is: 8
sizeof a+c+f which is of type int+float+long long is: 4

If you observe the above program, the sizeof operator tells you about the concept of data type broadening. Did you observed when you added int a with long e, the resultant has the size of 8 bytes which is the same as the size of long. So that means, though you have int as an operand, the result will have datatype as long due to the concept of data type broadening. This is also similar when you added float type c with double type 8, again we saw an instance of data type broadening. sizeof operators help you to validate the concept too.

sizeof operator to find sizeof an object

To find what size of an object is, we can use the sizeof operator easily. Normally the size of an object is the sum of its constituent data members. It's guaranteed that size of an object will never be smaller than that, but what compiler does is that compiler adds padding between data members to ensure alignment requirements of the platform. That's one can easily check that by using sizeof operator.

Example

Below is an example where the object has three data members, one string and two integers. So, the size should have been 8 (depends on compiler, one may check the size of string using sizeof operator) + 4 + 4 but it's 24 found by sizeof operator and that's due to compiler adding padding space.

#include <iostream>
using namespace std;

class student {
public:
    int roll;
    string name;
    int marks;
};

int main()
{
    student st;
    st.name = "xyz";
    st.roll = 1;
    st.marks = 80;
    printf("sizeof student object st is: %lu\n", sizeof(st));

    return 0;
}

Output:

sizeof student object st is: 24

sizeof operator to find array size

We can use sizeof operator to find array size. The array size will be array length* sizeof(datatype).

Example

#include <iostream>
using namespace std;

int main()
{
    int marks[20];
    cout << "sizeof the array marks is: " << sizeof(marks) << endl;
    return 0;
}

Output:

sizeof the array marks is: 80

sizeof operator also helps out to find the length of array very easily. The length of the array will be,

length of array= sizeof(array)/sizeof(datatype)

Example

Below is an example:

#include <iostream>
using namespace std;

int main()
{
    int arr[] = { 12, 76, 45, 10, 5, 1, 6, 17, 89 };
    cout << "length the array arr is: " << sizeof(arr) / sizeof(int) << endl;
    return 0;
}

Output:

length the array arr is: 9

Dynamic memory allocation using sizeof operator

Below is the example where we dynamically allocate memory using malloc() function where sizeof helps defining the size of a single element,

Example

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int* arr = (int*) malloc(sizeof(int) * 20);
 
    for (int i = 0; i < 10; i++)
        arr[i] = i;
 
    if (arr == NULL)
        printf("Memory couldn't be allocated\n");
    else
        printf("Memory got allocated\n");
        
    return 0;
}

Output:

Memory got allocated

Find output of programs - sizeof() Operator

Let's play with sizeof operator more and this can be serious brain-teasing.

Guess the output of the following codes.

Code 1

#include <bits/stdc++.h>
using namespace std;

int main()
{
    queue<int> q;
    stack<int> st;
    vector<int> a;
    
    cout << "size of the queue q is:" << sizeof(q) << endl;
    cout << "size of the stack st is:" << sizeof(st) << endl;
    cout << "size of the vector a is:" << sizeof(a) << endl;
    
    return 0;
}

Did you guess all the outputs to be 0 right? Since all are empty initially, it should be 0 for all. Clever mates!

Good guess.

Let's see the output now,

size of the queue q is:80
size of the stack st is:80
size of the vector a is:24

Oops! What the hell is that? How can be the size of an empty queue be 80? How can the size of the empty stack be 80? How can the size of an empty vector be 24?

Is there anything hidden?

Yes, the thing is sizeof gives you the memory acquired only. It doesn't care about any other thing. Whenever we use STL, there are implementations behind each of STL types like a queue, stack, vector, maps, etc. You can find the actual implementations behind the templates and you will find data members there which are contributing towards these outputs. So these objects instances having some memory occupied though those are empty.

Well, if you have guessed that it will have some output except 0, well done then.

Code 2

#include <bits/stdc++.h>
using namespace std;

int main()
{
    int* arr = (int*)(malloc(sizeof(int) * 10));

    for (int i = 0; i < 10; i++)
        arr[i] = i;

    cout << "size of arr is: " << sizeof(arr) << endl;
    
    return 0;
}

Probably you guessed it to be 40 which is sizeof(int)*10=4*10

Okay! Let's check the output,

size of arr is: 8

Oops! How can it be 8? It should give you the size of the array right as we saw in the Sizeof operator to find array size part.

But it's 8. The reason is its printing the size of the pointer and compiler generally allocated all pointers to be of 8 Bytes. So, it's not the same as printing the size of the array as it's a pointer only.

So, the output is 8

Code 3

#include <stdio.h>

void f(int a)
{
    a = 10;
    return;
}

int main()
{
    int a = 5;
    printf("sizeof function f: %lu\n", sizeof(f(a)));

    return 0;
}

Probably you guessed it 0 as it will return void and void means empty. Oh, you guessed it compilation error? Bravo!!

Let's see what it outputs,

sizeof function f: 1

This is something that may surprise you of course. This depends on the compiler and if you run in GNU c compiler you will find sizeof(void) to be 1. But in C++ it may throw warning or error.

void means empty and this is not compatible type as well, thus sizeof() should throw an error, but to our surprise, in GNU c it outputs 1 which is due to compiler having nonstandard extension.

In GNU C, addition and subtraction operations are supported on pointers to void and on pointers to functions. This is done by treating the size of a void or of a function as 1. A consequence of this is that sizeof is also allowed on void and function types, and returns

I hope this tutorial has helped you to know sizeof operator well and you had some brainteasers too. Lastly, a very important fact is sizeof operator can't be overloaded.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.