sizeof Operator: Compile-time or Run-time?


In C/C++ we use sizeof operator in C/C++ to calculate the size of any datatype. To use the operator to the fullest it is important to understand whether this operator works at compile-time or run-time. Well, a compile-time operator means that gets evaluated entirely at the time of compilation. Let us take an example
#include <stdio.h>
int main(void)
{
            int i = 10;
            int* j = new int [i];
            int k[] = {10, 2, 3, 4};
            int* l = k;
           
            printf("size of int = %d\n", sizeof(int));
            printf("size of i = %d\n", sizeof(i));
            printf("size of j = %d\n", sizeof(*j));
            printf("size of k = %d\n", sizeof(k));
            printf("size of l = %d\n", sizeof(l));

            delete [] j;
            return 0;
}

In C++ programming language, sizeof works at compile-time. In the code given above, all the call to sizeof [i.e. sizeof(int), sizeof(i), sizeof(k), sizeof(l)]  can be entirely evaluated at the compile-time and so the above piece of code is valid. The output of this program would be as below:

size of int = 4
size of i = 4
size of j = 4
size of k = 16
size of l = 4

Note that in above example the size of array k is known at the compile time. Whereas it is impossible for compiler to determine the size of dynamic array j.

Difference in behavior of sizeof in C and C++:
  • C language(C99 standard) supports variable-length arrays (VLAs) and for which the ‘sizeof’ operator does not necessarily evaluate to a compile-time value;  it can also be evaluated at runtime.
  • Whereas C++ language supports templates and for which the ‘sizeof’ need to be evaluated at compile-time only.
You can learn few more interesting points about sizeof at the following link:
sizeof Operator: Compile-time or Run-time? sizeof Operator: Compile-time or Run-time? Reviewed by Sourabh Soni on Thursday, August 02, 2012 Rating: 5

No comments

Post a Comment