Reputation: 31
Is there a method to calculate the size of a variable without using any predefined functions? I read somewhere that it can be done using bit manipulation, but I'm not sure.
This is an answer (finding the size of integer without using sizeof), but I want a better approach in C++ which shall be algorithmic (without using a predefined function.
Upvotes: 0
Views: 277
Reputation: 238401
Is there a method to calculate the size of a variable without using any predefined functions?
Yes. You can use the sizeof
operator. sizeof
is not a function.
calculate size of an integer/any data type without using
sizeof(*type)
?
If you have an object of such type, then pointer arithmetic is one way. There is an example of this in the page linked in the question. But there is generally no need to use such hack.
Another - limited - trick is to use std::numeric_limits
(although its implementation probably internally uses sizeof
). This works only with integer types (assuming no padding bits; will work for unsigned integers, may in theory fail with signed ones):
using T = int; // example
static_assert(std::is_integral_v<T> &&
std::has_unique_object_representations_v<T>);
auto size = ( std::numeric_limits<T>::digits
+ std::numeric_limits<T>::is_signed) / CHAR_BIT;
but I want a better approach
sizeof
operator is the better approach, compared to the tricks mentioned above.
Upvotes: 1