Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the cost of sizeof?

Tags:

c++

What is the cost of sizeof?

I would expect:

  • sizeof(someclass) can be known at compile time
  • sizeof(someStaticArray) can be known at compile time
  • sizeof(someDynamicArray) can not be known at compile time

So how does that last case work?

like image 625
David Avatar asked Oct 20 '11 15:10

David


People also ask

What is the meaning of sizeof?

sizeof is a unary operator in the programming languages C and C++. It generates the storage size of an expression or a data type, measured in the number of char-sized units.

What is sizeof example?

The sizeof operator applied to a type name yields the amount of memory that can be used by an object of that type, including any internal or trailing padding. The result is the total number of bytes in the array. For example, in an array with 10 elements, the size is equal to 10 times the size of a single element.

How do you calculate sizeof?

We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);

What type is sizeof?

Sizeof is a much used operator in the C or C++. It is a compile time unary operator which can be used to compute the size of its operand. The result of sizeof is of unsigned integral type which is usually denoted by size_t.


2 Answers

The sizeof construct in C is a completely compile time construct. There is no runtime cost.

There is at least one exception to this rule: variable length arrays. The size of these arrays are computed at runtime and that size is reused for any sizeof operators applied to them.

Please note there is a difference between a variable length array and a dynamic one. Variable length arrays were added in C99 and they do support the sizeof operator

  • http://en.wikipedia.org/wiki/Sizeof
like image 83
JaredPar Avatar answered Sep 19 '22 18:09

JaredPar


sizeof(dynamicArray) will just return sizeof(pointer) because in c/c++ dynamic arrays are just pointers.

like image 33
Dan F Avatar answered Sep 20 '22 18:09

Dan F