Variable size/Get

From Rosetta Code
Revision as of 19:10, 27 February 2007 by Ce (talk | contribs) (C++)
Task
Variable size/Get
You are encouraged to solve this task according to the task description, using any language you may know.

Demonstrate how to get the size of a variable.

Ada

Ada represents the size of a variable in bits, not bytes like many other languages.

Int_Bits : constant Integer := Integer'size;
Whole_Bytes : constant Integer := Int_Bits / Storage_Unit; -- Storage_Unit is the number of bits per storage element

C++

Store the size of an int (in bytes):

#include <cstdlib>
std::size_t intsize = sizeof int;

Note: sizeof can be used without the header <cstdlib>; the latter is only needed for the type std::size_t, which is an alias for whatever type is used to store sizes for the given compiler.

Output the number of bits of an int:

#include <climits>
#include <cstdlib>
std::size_t intbits = CHAR_BITS*sizeof int;

IDL

IDL is array based, so its size() function is geared towards that:

arr = intarr(3,4)
print,size(arr)
;=> prints this:
       2           3           4           2          12

The result means: 2 dimensions in the array, the first dimension has extent 3, the second has extent 4, the elements of the array are 2-byte integers (IDL's default for an "int"), there's a total of 12 elements in the array.


Perl

Interpreter: Perl 5.x

Modules: Devel::Size

use Devel::Size;
my $var = 9384752;
my @arr = (1, 2, 3, 4, 5, 6);
print size($var);
print total_size(@arr);

Tcl

Since all variables are ultimately strings in Tcl, this is easy:

string bytelength $var