Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

size of a datatype without using sizeof

Tags:

c

sizeof

I have a data type, say X, and I want to know its size without declaring a variable or pointer of that type and of course without using sizeof operator.

Is this possible? I thought of using standard header files which contain size and range of data types but that doesn't work with user defined data type.

like image 680
sud03r Avatar asked Aug 02 '09 16:08

sud03r


2 Answers

To my mind, this fits into the category of "how do I add two ints without using ++, += or + ?". It's a waste of time. You can try and avoid the monsters of undefined behaviour by doing something like this.

size_t size = (size_t)(1 + ((X*)0)); 

Note that I don't declare a variable of type or pointer to X.

like image 59
CB Bailey Avatar answered Sep 22 '22 04:09

CB Bailey


Look, sizeof is the language facility for this. The only one, so it is the only portable way to achieve this.

For some special cases you could generate un-portable code that used some other heuristic to understand the size of particular objects[*] (probably by making them keep track of their own size), but you'd have to do all the bookkeeping yourself.

[*] Objects in a very general sense rather than the OOP sense.

like image 22
dmckee --- ex-moderator kitten Avatar answered Sep 22 '22 04:09

dmckee --- ex-moderator kitten