What is the cost of sizeof?
I would expect:
So how does that last case work?
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.
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.
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]);
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.
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
sizeof(dynamicArray)
will just return sizeof(pointer)
because in c/c++ dynamic arrays are just pointers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With